package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.filter.WmTokenFilter;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper,
        WmMaterial> implements WmMaterialService {


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    FastDFSClient fastDFSClient;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    /**
     * 上传素材图片
     * @param file
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile file) {
        if (file==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        try {
            String path = fastDFSClient.uploadFile(file);

            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(path);
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            WmUser wmUser = WmThreadLocalUtils.getUser();
            if (wmUser!=null){
                wmMaterial.setUserId(wmUser.getId());
            }
            this.save(wmMaterial);
            wmMaterial.setUrl(fileServerUrl+path);
            return ResponseResult.okResult(wmMaterial);

        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 获取素材信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        dto.checkParam();

        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取当前用户的id
        Integer id = WmThreadLocalUtils.getUser().getId();
        lambdaQueryWrapper.eq(WmMaterial::getUserId,id);
        //是否收藏
        if (dto.getIsCollection()!=null && dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //倒序排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        Page page = new Page(dto.getPage(),dto.getSize());
        IPage result = page(page,lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),
                dto.getSize(), (int) result.getTotal());

        List<WmMaterial> records = result.getRecords();

        //为每个图加前缀
        records=records.stream().map(a->{
            a.setUrl(fileServerUrl+a.getUrl());
            return a;
        }).collect(Collectors.toList());
        responseResult.setData(records);

        return responseResult;
    }

    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delWmMaterial(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        String replace = wmMaterial.getUrl().replace(fileServerUrl, "");
        try {
            fastDFSClient.delFile(replace);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        this.removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public ResponseResult cancleCollectionMaterial(Integer id, Short status) {
        //参数校验
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前用户的id
        Integer uid = WmThreadLocalUtils.getUser().getId();

        if (uid==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,status)
                .eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,uid));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
